<template>
  <view class="login-container">
	  <view class="login-box">
		  <view class="box-img"><image src="/static/login.png"></image></view>
		  <text class="box-apply">申请获取以下权限</text>
		  <text class="box-fetch">获取你的公开信息（昵称、头像、地区等）</text>
		  <button @click="getUserProfile">微信登录</button>
	  </view>
  </view>
</template>

<script setup>
import { ref,onMounted } from 'vue';
import { login as apiLogin } from '@/api/user';

const code = ref('');

// 第一步：先获取用户信息
const getUserProfile = async () => {
  try {
    // 1. 先获取用户信息（必须由按钮直接触发）
    const { rawData, signature } = await wx.getUserProfile({
      desc: '用于完善会员资料'
    });
    
    // 2. 获取登录code
    const loginRes = await wx.login();
    code.value = loginRes.code;
    
    // 3. 执行登录
    await handleLogin(rawData, signature);
  } catch (error) {
    console.error('获取用户信息失败:', error);
    uni.showToast({ title: '授权失败', icon: 'none' });
  }
};

// 第二步：执行登录
const handleLogin = async (rawData, signature) => {
  uni.showLoading({ title: '登录中...', mask: true });
  
  try {
    const res = await apiLogin({
      code: code.value,
      rawData,
      signature
    });

    if (res.code === '200') {
      uni.setStorageSync('token', res.data);
       uni.setStorageSync('wxUserInfo', rawData); // 存储微信用户信息
       uni.navigateTo({ url: '/pages/user/info' });
    }else {
      console.error('登录请求失败，状态码:', res.statusCode);
    }
  } catch (error) {
    uni.showToast({ title: '登录失败', icon: 'none' });
	   console.error('登录过程失败:', error);
  } finally {
    uni.hideLoading();
  }
};

onMounted(() => {
		  // 检查是否已填写过信息
		  const hasCompletedInfo = uni.getStorageSync('hasCompletedInfo');
		  if (hasCompletedInfo) {
		    uni.switchTab({ url: '/pages/home/home' });
		  } 
		});

</script>
<style lang="scss">
	.login-container{
		height: 100vh;
		background-image: url(https://zhoukaiwen.com/img/loginImg/bg3.png);
		position: relative;
		.login-box{
			width: 700rpx;
			height: 600rpx;
			position: absolute;
			top: 300rpx;
			left: 50%;
			transform: translate(-50%);
			background-color: #ffffff;
			border-radius: 20rpx;
			box-shadow: 0 5px 7px 0 rgba(0, 0, 0, 0.15);
			z-index: 9;
			.box-img{
				width: 400rpx;
				height: 300rpx;
				position: absolute;
				left: 50%;
				height: 300rpx;
				transform: translate(-50%);
				image{
					width: 100%;
					height: 100%;
				}
			}
			.box-apply{
				font-size: 25rpx;
				position: absolute;
				top: 300rpx;
				left: 60rpx;
			}
			.box-fetch{
				font-size: 25rpx;
				color: #666;
				position: absolute;
				top: 350rpx;
				left: 60rpx;
			}
			button{
				position: absolute;
				bottom: 30rpx;
				left: 50%;
				transform: translate(-50%);
				width: 600rpx;
				font-size: 28rpx;
				background: linear-gradient(to right, #ff8f77, #fe519f);
				color: #fff;
				height: 90rpx;
				line-height: 90rpx;
				border-radius: 50rpx;
			}
		}
	}
</style>